package com.huizu.common.utils;

import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
import com.google.zxing.common.BitMatrix;
import com.huizu.common.config.RuoYiConfig;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * 二维码
 */
public class QRCodeGenerator {

    public static void main(String[] args) {
        String id = "123456"; // 你的ID
        String content = "https://example.com"; // 二维码内容，可以是URL等

//        // 生成二维码
//        BufferedImage qrImage = QrCodeUtil.generate(content, QrConfig.create());
//
//        // 在二维码下面添加ID
//        BufferedImage resultImage = addIdToQrCode(qrImage, id);
//
//        // 输出到文件
//        File outputFile = new File("output.png");
//        try {
//            ImageIO.write(resultImage, "png", outputFile);
//            System.out.println("二维码生成成功，已保存到：" + outputFile.getAbsolutePath());
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
    }



    private static BufferedImage toBufferedImage(BitMatrix matrix) {
        int width = matrix.getWidth();
        int height = matrix.getHeight();
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                if (matrix.get(x, y)) {
                    image.setRGB(x, y, Color.BLACK.getRGB());
                } else {
                    image.setRGB(x, y, Color.WHITE.getRGB());
                }
            }
        }
        return image;
    }

    public static String getCodeImageOss(String pr,String id){


        // 生成二维码
        BufferedImage qrImage = QrCodeUtil.generate(pr+id, QrConfig.create());

        // 在二维码下面添加ID
        BufferedImage resultImage = addIdToQrCode(qrImage, id);
        // 读取图片文件并创建BufferedImage对象

        byte[] buffer = null;
        FileInputStream fis;
        File file = new File("/www/SpringBootProjects/zhuisu/upload/"+id+".png");

//        File file = new File("E:\\huizhu/追溯app/upload/"+id+".png");
        BufferedImage image = null;
        try {
            ImageIO.write(resultImage, "png", file);
//            image = ImageIO.read(file);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            fis = new FileInputStream(file);
            byte[] b = new byte[1024];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            fis.close();
            bos.close();
            buffer = bos.toByteArray();
            System.out.println("转换成功！");
            String s = OssUtil.insertByte(buffer);
            if(file.exists()) {
                file.delete();
            }
            return s;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

    public static String getCodeImage(HttpServletRequest request,String id,String url){

        // 上传文件路
        String filePath = RuoYiConfig.getUploadPath();
        //
        String domain = getDomain(request);

        String content = "https://example.com"; // 二维码内容，可以是URL等

        // 生成二维码
        BufferedImage qrImage = QrCodeUtil.generate(content, QrConfig.create());

        // 在二维码下面添加ID
        BufferedImage resultImage = addIdToQrCode(qrImage, id);

        // 输出到文件
        String s = filePath + "/" + id +".png";

        File outputFile = new File(s);
        try {
            ImageIO.write(resultImage, "png", outputFile);
            url = domain+"/profile/upload/"+id+".png";
            System.out.println("二维码生成成功，已保存到：" + outputFile.getAbsolutePath());
            return url;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return url;
    }

    public static String getDomain(HttpServletRequest request)
    {
        StringBuffer url = request.getRequestURL();
        String contextPath = request.getServletContext().getContextPath();
        return url.delete(url.length() - request.getRequestURI().length(), url.length()).append(contextPath).toString();
    }

    public static BufferedImage addIdToQrCode(BufferedImage qrImage, String id) {
        // 创建画布
        BufferedImage resultImage = new BufferedImage(qrImage.getWidth(), qrImage.getHeight() + 40, BufferedImage.TYPE_INT_RGB);
        Graphics2D graphics = resultImage.createGraphics();
        graphics.drawImage(qrImage, 0, 0, null);

        // 在二维码下面绘制ID文本
        graphics.setColor(Color.blue);
        graphics.setFont(new Font("Arial", Font.PLAIN, 20));
        FontMetrics fontMetrics = graphics.getFontMetrics();
        int textWidth = fontMetrics.stringWidth(id);
        graphics.drawString(id, (qrImage.getWidth() - textWidth) / 2, qrImage.getHeight() + 30);

        graphics.dispose();
        return resultImage;
    }
}
